package com.matrix.order.infrastructure.gateway.acl;

import com.matrix.api.product.ProductApi;
import com.matrix.api.product.vo.ProductVO;
import com.matrix.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcException;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 有点甜
 * @since 2025/8/2
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProductAcl {

    @DubboReference(check = false, timeout = 2000)
    private ProductApi productApi;

    public Map<Long, ProductVO> getProductsByIds(List<Long> productIds) {
        if (productIds == null || productIds.isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            List<ProductVO> productList = productApi.getProductsByIds(productIds);
            if (productList == null) {
                throw new BusinessException("获取菜品信息失败,请稍后再试");
            }
            return productList.stream().collect(Collectors.toMap(ProductVO::getId, Function.identity()));
        } catch (RpcException e) {
            log.error("获取菜品信息失败, productIds: {}, RPC异常: {}", productIds, e.getMessage());
            throw new BusinessException("商品服务暂不可用,请稍后重试");
        }
    }
}